import React, { Component } from 'react';
import { List, InputItem, Button, Flex, Toast } from 'antd-mobile';
import { createForm } from 'rc-form';
import { Link } from 'react-router-dom';

import '../css/common.css';
import '../css/login.css';

class applyLogin extends Component {
  // get code
  idencode=()=>{
    let formData = new FormData();
    let phone = this.props.form.getFieldValue('phone');
    if( typeof(phone)==="undefined" ){
      Toast.info('请输入正确手机号码，才能获取验证码！',2);
    }else{
      phone = phone.replace(/\s+/g, "");
      formData.append("phone",phone);
      fetch('http://58.220.10.23:8001/api/sms/sendCheckCodeWhenRegister', {
        method: 'POST',
        credentials: 'include',
        body: formData,
      }).then(response => response.json())
      .then(data=>{
         if( data.status===0 ){
           Toast.success('验证码获取成功！', 2);
         }else{
           Toast.fail(data.errorMsg, 2);
         }
      })
    }
  }

  pwLogin=(e)=>{
    this.props.form.validateFields((error, value) => {
      if( error ){
        Toast.info('请填写完整的信息 !!!', 2);
        return;
      }else{
        // submit
        value.phone = value.phone.replace(/\s+/g, "");
        let _url = `http://58.220.10.23:8001/api/user/login?account=${value.phone}&verifycode=${value.verifycode}`;
        fetch(_url, { method: 'POST', credentials: 'include',
    	   }).then(response => response.json())
    	   .then(data=>{
            //console.log(data);
            if( data.status==0 ){
              Toast.success('登录成功！', 2);
              this.props.history.push('applyForm');
            }else{
              Toast.fail(data.errorMsg, 2);
            }
    	   })
      }
    });
  }

  render() {
    const { getFieldProps } = this.props.form;
    return (
      <div>
        <List>
          <Flex>
            <p className="title">借款人登录</p>
          </Flex>
          <Flex>
            <Flex.Item className="phoneForIden">
              <InputItem
                {...getFieldProps('phone',{rules: [{required: true}]} )}
                type="phone"
                placeholder="请输入手机号"
                clear
                moneyKeyboardAlign="left"
              ></InputItem>
            </Flex.Item>
            <Flex.Item className="idenBtn">
              <Button type="ghost" size="small" onClick={this.idencode} >获取验证码</Button>
            </Flex.Item>
          </Flex>
          <InputItem
            {...getFieldProps('verifycode',{ rules: [{required:true}] })}
            placeholder="请输入验证码"
            clear
          ></InputItem>
          <List.Item>
            <Button type="primary" onClick={this.pwLogin}>登录</Button>
          </List.Item>
          <List.Item>
            <Link to="/applyLogin" id="togglefor-pw" className="btn-toggle">切换到账号密码登录</Link>
          </List.Item>
        </List>
      </div>


    );
  }
}

const _applyLogin = createForm()(applyLogin);
export default _applyLogin;
